import numpy as np
import sys
import matplotlib
import matplotlib.pyplot as plt
import imageio
from matplotlib import animation
sys.setrecursionlimit(1000000)

rate_01=[]
image=[]
fig = plt.figure()

def matrix(i):
    rate1=i/100
    rate0=1-rate1
    mat=np.random.choice([0,1],size=(150,150),p=[rate0,rate1])
    rate_01.append(rate1)
    print("when rate =",rate1)
    print(mat)
    return mat

for i in range(1,101):
    new_mat=matrix(i)
    def show(table):
        row1 = len(new_mat)
        col1 = len(new_mat[0])
        for i in range(row1):
            for j in range(col1):
                print(table[i][j], end=" ")
            print()
    #show(new_mat)

    num = 0
    for m in range(0, 150):
        for n in range(0, 150):
            a = new_mat[m][n]
            if (a == 1):
                num = num + 1
            if (a == 0):
                num = num

    print("num=", num)
    rows = len(new_mat)
    cols = len(new_mat[0])
    label_table = []
    for i in range(rows):
        col = cols * [0]
        label_table.append(col)

    def dfs(i, j, mask):
        if i < 0 or i >= rows or j < 0 or j >= cols or label_table[i][j] != 0 or new_mat[i][j] != 1:
            return 0
        label_table[i][j] = mask
        ret = 1
        ret += dfs(i, j - 1, mask)
        ret += dfs(i, j + 1, mask)
        ret += dfs(i - 1, j, mask)
        ret += dfs(i + 1, j, mask)
        return ret

    res = {}
    mask = 1
    for i in range(rows):
        for j in range(cols):
            if new_mat[i][j] == 1 and label_table[i][j] == 0:
                ret = dfs(i, j, mask)
                res[mask] = ret
                mask += 1

    sorted_res = [(k, res[k]) for k in sorted(res, key=res.get, reverse=True)]
    print(sorted_res)
    print(rate_01)

    max_grp_num=[]
    second_grp_num=[]
    for p in range(0,len(label_table)):
        for q in range(0,len(label_table[0])):
            y=label_table[p][q]
            if(len(sorted_res)>1):
                max_grp=sorted_res[0][0]
                sec_grp = sorted_res[1][0]
                if (y==max_grp):
                    label_table[p][q]=2
                elif (y==sec_grp):
                    label_table[p][q]=1
                else:
                    label_table[p][q]=0

            if(len(sorted_res)<=1):

                max_grp=sorted_res[0][0]
                if(y==max_grp):
                    label_table[p][q]=2
                else:

                    label_table[p][q]=0

    x = label_table
    im=plt.matshow(x, cmap=plt.cm.Greens)
    image.append(im)
    plt.title("matrix MAX - SEC")

plt.close()
ani = animation.ArtistAnimation(fig, image, interval=450, repeat_delay=3000)
ani.save("Pendulum_Animation.gif", writer='pillow', fps=1000 / 50)
plt.show()




